import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { errorRouter, staticRouter } from '@/routers/staticRouter';
import { GlobalStore } from '@/stores/global';
import { LOGIN_ROUTE_NAME, OAUTH2_CALLBACK_NAME } from '@/routers/constants';
import { Notification } from '@arco-design/web-vue';
import { encode } from 'js-base64';
import { RouteStore } from '@/stores/route';
import { initDynamicRouter } from '@/routers/dynamicRouter';

NProgress.configure({
	easing: 'ease', // 动画方式
	speed: 500, // 递增进度条的速度
	showSpinner: false, // 是否显示加载ico
	trickleSpeed: 200, // 自动递增间隔
	minimum: 0.3, // 初始化时的最小百分比
});

const router = createRouter({
	history: createWebHashHistory(''),
	routes: [...staticRouter, ...errorRouter],
});

/**
 * @description 路由拦截 beforeEach
 * */
router.beforeEach(async (to, from, next) => {
	// 每次切换页面时，调用进度条
	NProgress.start();
	const globalStore = GlobalStore();
	globalStore.setRoute(String(to.name));
	// 判断当前页面是否需要鉴权
	if (to.meta.requiresAuth) {
		if (!globalStore.token || globalStore.token === '') {
			globalStore.resetUserInfo();
			router.replace({ name: LOGIN_ROUTE_NAME, query: { redirect: encode(to.name as string) } }).then((r) => {
				Notification.error({
					title: '登录超时',
					content: '登录超时，请重新登陆',
				});
			});
		} else {
			// 正常跳转页面
			await nextRoute(to, next);
		}
	} else {
		// 正常跳转页面
		await nextRoute(to, next);
	}
});

/**
 * @description 路由跳转结束
 * */
router.afterEach(() => {
	NProgress.done();
});

const nextRoute = async (to: any, next: any) => {
	const routeStore = RouteStore();
	// 如果没有菜单列表，就重新请求菜单列表并添加动态路由
	if (!routeStore.routeList.length && to.name !== LOGIN_ROUTE_NAME && to.name !== OAUTH2_CALLBACK_NAME) {
		await initDynamicRouter();
		return next({ ...to, replace: true });
	} else {
		next();
	}
};
export default router;
